
package org.soekrat.engine.rethor;


public final class HtmlSentenceRenderer extends SentenceRenderer 
{

  @Override
  public String render(String sentence) 
  {
    StringBuilder sb=new StringBuilder();
    
    int lastStart=0;
    
    int[] urls=findHttpUrl(0, sentence);
    while (urls!=null)
    {
      String beforeUrl=sentence.substring(lastStart, urls[0]);
      sb.append(beforeUrl);
      
      lastStart=urls[1];
      
      String url=sentence.substring(urls[0], urls[1]);
      sb.append("<a href='").append(url).append("'>").append(url)
        .append("</a>");
      
      urls=findHttpUrl(urls[1], sentence);
    }
    
    if (lastStart<sentence.length()) sb.append(sentence.substring(lastStart));
     
    sentence=sb.toString();
    
    return renderStart(sentence);
  }
  
  private int[] findHttpUrl(int start, String sentence)
  {
    int idx0=sentence.indexOf("http://", start);
    if (idx0==-1) return null;
    return new int[]{ idx0, tokenEndScan(idx0, sentence) };
  }
  
  private int tokenEndScan(int start, String sentence)
  {
    int n=sentence.length();
    if (start>=n) return n;
    for (int i=start; i<n; i++)
    {
      char c=sentence.charAt(i);
      if (Character.isWhitespace(c)) return i;
    }
    return n;
  }
  
}
